import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.management.ManagementFactory;
import javax.management.MBeanServer;
import javax.management.ObjectName;

public class MemTest {

    public static void main(String[] args) {
        System.out.println(getSystemMemUsage());

        System.out.println(getMemoryUsage());
    }


    private static Double getSystemMemUsage() {

        try {

            MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
            ObjectName name = ObjectName.getInstance("java.lang:type=OperatingSystem");

            long freePhysicalMemorySize = (Long) mbs.getAttribute(name, "FreePhysicalMemorySize");
            long totalPhysicalMemorySize = (Long) mbs.getAttribute(name, "TotalPhysicalMemorySize");

            System.out.println("freePhysicalMemorySize:" + freePhysicalMemorySize);
            System.out.println("totalPhysicalMemorySize:" + totalPhysicalMemorySize);
            return (totalPhysicalMemorySize - freePhysicalMemorySize) / 1.0 / totalPhysicalMemorySize;

        } catch (Exception e) {
            return 0.0;
        }
    }

    //获取内存使用率
    public static float getMemoryUsage() {
        float memUsage = 0.0f;
        Process pro = null;
        Runtime r = Runtime.getRuntime();
        BufferedReader in = null;
        try {
            String command = "cat /proc/meminfo";
            pro = r.exec(command);
            in = new BufferedReader(new InputStreamReader(pro.getInputStream()));
            String line;
            long totalMem = 0, freeMem = 0, cachedMem = 0;
            while ((line = in.readLine()) != null) {
                String[] memInfo = line.split("\\s+");

                if (memInfo[0].startsWith("MemTotal")) {
                    totalMem = Long.parseLong(memInfo[1]);
                }
                if (memInfo[0].startsWith("MemFree")) {
                    freeMem = Long.parseLong(memInfo[1]);
                }
                if (memInfo[0].startsWith("Cached")) {
                    cachedMem = Long.parseLong(memInfo[1]);
                }
            }
            /***
             * 只取整数
             */
            return Math.round(((float) (totalMem - freeMem - cachedMem) / totalMem) * 100);

        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw));
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
            if (pro != null) {
                pro.destroy();
            }
        }
        return memUsage;
    }
}